﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.IO;

namespace MediaPlayer.Model
{
	[Serializable]
	public class PlayList
	{
        [XmlIgnore]
        private const string playListFile = "PlayList.xml";

        public string Name
        {
            get;
            set;
        }

        public List<Song> SongList
        {
            get;
            set;
        }

        public PlayList()
        {
            this.Name = "PlayList";
            this.SongList = new List<Song>();
        }

        public PlayList(string name)
        {
            this.Name = name;
            this.SongList = new List<Song>();
        }


		public void AddSong(Song song)
		{
			this.SongList.Add(song);
		}

		public void RemoveSong(Song song)
		{
			if (this.DoesSoundIsInList(song) == true)
				this.SongList.Remove(song);
		}

		private bool DoesSoundIsInList(Song song)
		{
			return this.SongList.Exists(new Predicate<Song>( (Song) =>
			{
				if (song.Name == Song.Name)
					return true;
				return false;
			}));
		}

        public static IEnumerable<PlayList> GetPlayListFromXml()
        {
            IEnumerable<PlayList> list;
            try
            {
                using (var fs = new FileStream(playListFile, FileMode.Open))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<PlayList>));

                    list = serializer.Deserialize(fs) as List<PlayList>;
                }
            }
            catch (Exception)
            {
                list = new List<PlayList>();
            }
            return list;
        }

        public static void SetPlayListToXml(List<PlayList> listToSerialize)
        {
            using (var fs = new FileStream(playListFile, FileMode.Create))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<PlayList>));

                serializer.Serialize(fs, listToSerialize);
            }
        }
    }
}
